//
//  YLUITabBar.swift
//  weiBo
//
//  Created by 杨雷 on 2016/11/30.
//  Copyright © 2016年 Yang.L. All rights reserved.
//

import UIKit

//protocol YLTabBarDelegate :NSObjectProtocol {
//    func didSelectedBtn ()
//}



class YLTabBar: UITabBar {

    //定义代理
//    var YLDelegate: YLTabBarDelegate?
    
    
    //定义闭包
    var callBack: (()->())?
    
    //MARK: - 懒加载
    private lazy var btn:UIButton = {
        
        let btn = UIButton()
        //设置背景图片
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: UIControlState.normal)
        
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), for: UIControlState.selected)
        
        //设置按钮图片
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), for: UIControlState.normal)
        
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), for: UIControlState.selected)
        
        //设置大小
        btn.sizeToFit()
        
        //添加点击事件
        btn.addTarget(self, action: #selector(clickBtnAction), for: UIControlEvents.touchUpInside)
        
        return btn
    }()
    
    //点击加号按钮事件
    @objc private func clickBtnAction () {
        
//        YLDelegate?.didSelectedBtn()
        
        callBack?()
    }
    
    
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //添加控件
    private func setupUI(){
        
        addSubview(btn)
        
        self.backgroundImage = UIImage(named: "tabbar_background")
        
    }
    
    //调整子控件布局
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        //中间加号的位置
        btn.center.x = width / 2
        btn.center.y = height / 2
        
        //计算每个tabbar宽
        let tabBarW = width / 5
        
        //记录第几个tabbar
        var index = 0
        
        //遍历子控件
        for childView in subviews {
            
            if childView.isKind(of: NSClassFromString("UITabBarButton")!) {
                
                //设置控件宽
                childView.width = tabBarW
                
                //设置x坐标
                childView.x = CGFloat(index) * tabBarW
                
                index += 1
                
                //给中间位置空出来
                if index == 2 {
                    
                    index += 1
                }
                
            }
            
        }
        
    }
    
}
